var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser')
const JwtUtil = require('./util/jwt');


var indexRouter = require('./routes/index');
// var usersRouter = require('./routes/users');
const systemRouter = require('./routes/system');
const siteRouter = require('./routes/site');
const firewallRouter = require('./routes/firewall');
const monitorRouter = require('./routes/monitor');
const crontabRouter = require('./routes/crontab');
const systemsetRouter = require('./routes/systemset');
const pluginRouter = require('./routes/plugin');
const fileRouter = require('./routes/file');
const wxRouter = require('./routes/wechat');


var app = express();


// 跨域
app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With,token');
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    if (req.method == 'OPTIONS') {
        res.sendStatus(200)
    } else if (!['/login', '/', '/token'].includes(req.url)) {
        //微信小程序跳过验证
        let user_agent = req.headers["user-agent"];
        if (user_agent != null && user_agent.indexOf('MicroMessenger') >= 0) {
            next();
            return;
        }
        let token = req.headers.token;
        let jwt = new JwtUtil(token);
        let result = jwt.verifyToken();
        // 如果考验通过就next，否则就返回登陆信息不正确
        if (result == 'err') {
            res.send({ status: false, reLogin: true, msg: '登录已过期,请重新登录' });
            // res.render('login.html');
        } else {
            next();
        }
    } else {
        next();
    }
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 静态页面
app.use('/', express.static('public'));
// 登录
app.use('/', indexRouter);
// 系统状态相关接口
app.use('/System', systemRouter)
// 系统设置
app.use('/SystemSet', systemsetRouter);
// 网站相关
app.use('/Site', siteRouter);
// 系统设置
app.use('/Monitor', monitorRouter);
// 系统安全
app.use('/Firewall', firewallRouter)
// 文件关联
app.use('/File', fileRouter)
// 计划任务
app.use('/Crontab', crontabRouter);
// 应用商店
app.use('/Plugin', pluginRouter);
// 微信小程序
app.use('/Wx', wxRouter);


app.all('*', function (req, res) {
    res.json({ 'status': false, 'msg': '无效请求' });
});



module.exports = app;
